<?php

class CreateAction extends CAction {

	public function run() {
		$this->controller->layout = 'project';
		$model = new Meetings;
		$model->project_id = $this->controller->project->id;
		$model->completed = Constants::FALSE;
		if (isset ($_POST['Meetings'])) {
			if (isset ($_POST['Meetings']['meeting_date'])) {
				$_POST['Meetings']['meeting_date'] = MeetingController::convert_date($_POST['Meetings']['meeting_date'], 'dd/MM/yyyy', 'yyyy-MM-dd');
			}
			$model->attributes = $_POST['Meetings'];
			if ($this->saveNewModel($model)) {
				$this->controller->redirect(array (
					'previousObjectives',
					'id' => $model->id, 
					'project_id' => $model->project_id
				));
			} else {
				$model->meeting_date = MeetingController::convert_date($model->meeting_date, 'yyyy-MM-dd', 'dd/MM/yyyy');
			}
		} else {
			$model->meeting_date = date("d/m/Y");
		}
		$this->controller->render('create', array (
			'model' => $model
		));
	}

	private function saveNewModel(& $model) {
		$r = true;
		$id = $model->project_id;
		// 1. create a new transaction
		$transaction = Yii::app()->db->beginTransaction();

		$sql = "update " . $model->tableName() . " set completed = 1 where project_id=:project and completed=0";
		$command = Yii::app()->db->createCommand($sql);
		$command->bindParam(':project', $id, PDO::PARAM_INT);
		$command->execute();

		if ($this->controller->project->meetings[0]->meeting_date > $model->meeting_date) {
			$model->addError('meeting_date', Yii::t('project', 'Meeting date must be greater than {date}', array (
				'{date}' => MeetingController::convert_date($this->controller->project->meetings[0]->meeting_date, 'yyyy-MM-dd', 'dd/MM/yyyy')
			)));

			return false;
		}

		foreach ($this->controller->project->meetings as $meeting) {
			if ($meeting->meeting_date == $model->meeting_date) {
				$model->addError('meeting_date', Yii::t('project', 'Another meeting exists on {date}', array (
					'{date}' => MeetingController::convert_date($model->meeting_date, 'yyyy-MM-dd', 'dd/MM/yyyy')
				)));

				return false;
			}
		}

		if (!$model->save()) {
			$r = false;
		}

		if (!$r) {
			$transaction->rollBack();
		} else {
			$transaction->commit();
		}

		return $r;
	}
	
}
?>
